var express = require('express');
var router = express.Router();
const {
  Op,
  where
} = require("sequelize")

const Users = require('../models/User').Users
const Classifications = require('../models/User').Classifications
const Matters = require('../models/User').Matters
const Orders = require('../models/User').Orders
const Notes = require('../models/User').Notes


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

// 个人信息-注册
router.post('/Register', async function (req, res, next) {
  const Reg = await Users.create({
    Name: '一朝',
    Phone: '17688776124',
    Password: '123456',
  })
})

// 个人信息-获取个人信息内容
router.get('/userInfo', async function (req, res, next) {
  const userInfo = await Users.findAll({
    where: {
      Phone: {
        [Op.eq]: 17688776124
      }
    }
  })

  res.send({
    code: 200,
    data: {
      userInfo
    }
  })
});

// 个人信息-登录功能
router.post('/Login', [async function (req, res, next) { //检验账号
  const PhoneStu = await Users.findOne({
    where: {
      Phone: req.body.Phone
    }
  })
  if (PhoneStu === null) {
    res.status(500).send({
      msg: '手机号错误'
    })
    return;
  } else {
    next()
  }
}, async function (req, res) { // 检验密码
  const PasswordStu = await Users.findAll({
    where: {
      Phone: req.body.Phone
    }
  })
  if (PasswordStu[0].dataValues.Password == req.body.Password) {
    res.send({
      code: 200,
      data: '登录成功！'
    })
  } else {
    res.status(500).send({
      msa: '密码错误'
    })
  }
}]);

// 我的规划-创建分类    1-新增  2-修改
router.post('/newClass', async function (req, res, next) {
  console.log(req.headers.uid);
  const Info = req.body
  if (Info.command == 1) {
    const newClass = await Classifications.create({
      Name: Info.Name,
      Color: Info.Color,
      Icon: Info.Icon,
      UserId: req.headers.uid,
    })
    res.send({
      code: 200,
      data: '添加成功'
    })
  } else if (Info.command == 2) {
    const updateClass = await Classifications.update({
      Name: Info.Name,
      Color: Info.Color,
      Icon: Info.Icon,
      UserId: req.headers.uid,
    }, {
      where: {
        id: Info.id
      }
    })

    res.send({
      code: 200,
      data: '修改成功'
    })
  }
});

// 我的规划-删除分类
router.post('/DeleteClass', async function (req, res, next) {
  

  const Delete = await Classifications.destroy({
    where: {
      Id: req.body.ID
    }
  })

  res.send({
    code: 200,
    msg: '删除成功!'
  })
});

// 我的规划-创建事项    1-新增  2-修改  3-删除
router.post('/newthings', async function (req, res, next) {
  const Info = req.body
  if (Info.command == 1) {
    const newthings = await Matters.create({
      Name: Info.Name,
      State: Info.State, // 1-进行中  2-完成 0-未完成
      StartDate: Info.StartDate,
      grade: Info.grade, // 1-重要 2-高 3-中 4-低  5-未分级
      EndDate: Info.EndDate,
      Describe: Info.Describe,
      ClassificationId: Info.ClassificationId,
      UserId: req.headers.uid
    })
    res.send({
      code: 200,
      data: '',
      msg: '创建成功'
    })
  } else if (Info.command == 2) {
    const updatethings = await Matters.update({
      Name: Info.Name,
      State: Info.State,
      StartDate: Info.StartDate,
      EndDate: Info.EndDate,
      Describe: Info.Describe,
    }, {
      where: {
        Id: Info.Id
      }
    })
    res.send({
      code: 200,
      data: '修改成功'
    })
  }else if (Info.command == 3) {
    const detelethings = await Matters.destroy({
      where:{
        Id: Info.Id
      }
    })
    res.send({
      code:200,
      data:'删除成功！！'
    })
  }
});

// 我的规划-全部事项
router.get('/allthings', async function (req, res, next) { //获取分类
  const ClassData = await Classifications.findAll({
    where: {
      UserId: req.headers.uid
    },
    include: [{
      model: Matters,
    }],
    order: [
      ['id', 'asc'],
      ['Matters', 'State', 'asc']
    ]
  })
  res.send({
    code: 200,
    data: ClassData
  })
})

// 我的规划-单选框选择  1-完成  0-未完成
router.post('/setMattersStu', async function (req, res, next) {
  if (req.body.Stu == 1) {
    const setStu = await Matters.update({
      State: 0
    }, {
      where: {
        Id: req.body.Id
      }
    })
  } else {
    const setStu = await Matters.update({
      State: 1
    }, {
      where: {
        Id: req.body.Id
      }
    })
  }

  res.send({
    code: 200,
    data: '',
    msg: '事项状态设置成功'
  })
})

// 我的一天-获得数据
router.post('/oneDay', async function (req, res, next) {
  let time = req.body.myDate
  let time2 = time + 86400000;

  const oneDayData = await Orders.findAll({
    where: {
      [Op.and]: [{
        StartDate: {
          [Op.between]: [time, time2]
        },
        UserId: req.headers.uid
      }]
    },
    // include: {
    //   model: Matters
    // },
    order: [
      ['State', 'asc']
    ]
  })

  res.send({
    code: 200,
    data: oneDayData
  })
})

// 我的一天-新增订单
router.post('/AddOrder', async function (req, res, next) {
  const Info = req.body
  const AddOrderData = await Orders.create({
    State: Info.State,
    StartDate: Info.StartDate,
    MatterId: Info.MattersId,
    Describe: Info.Name + "-" + Info.Describe,
    UserId: req.headers.uid,
    Name: Info.Name
  })

  res.send({
    code: 200,
    data: '',
    msg: '创建任务成功'
  })
})

// 我的一天-删除订单
router.post('/DeleteOrders', async function (req, res, next) {
  const Delete = await Orders.destroy({
    where: {
      Id: req.body.ID
    }
  })

  res.send({
    code: 200,
    msg: '删除成功!'
  })
});

// 我的一天-关联事项
router.post('/HasMatter', async function (req, res, next) {
  const Options = await Matters.findAll({
    attributes: ['Name', 'Id'],
    where: {
      State: 0,
      EndDate: {
        [Op.gte]: req.body.myDate
      }
    }
  })

  res.send({
    code: 200,
    data: Options,
  })
})

// 我的一天-单选框选择 1-完成 0-未完成
router.post('/setOrdersStu', async function (req, res, next) {
  if (req.body.Stu == 1) {
    const setStu = await Orders.update({
      State: 0
    }, {
      where: {
        Id: req.body.Id
      }
    })
  } else {
    const setStu = await Orders.update({
      State: 1
    }, {
      where: {
        Id: req.body.Id
      }
    })
  }

  res.send({
    code: 200,
    data: '',
    msg: '任务状态设置成功'
  })
})

// 我的一周-获取数据
router.post('/WeekInfo', async function (req, res, next) {
  console.log(req.body.Target.TimeData);
  let Datt = new Date(req.body.Target.TimeData).getTime()
  
  // 获取今日的年月日
  // const year = Datt.getFullYear()
  // const month = Datt.getMonth()
  // const day = Datt.getDate()
  // const week = Datt.getDay()

  // 计算本周开始日期和结束日期
  let WeekStartDate = Datt
  let WeekEndDate = WeekStartDate + 604800000

  const WeekData = await Orders.findAll({
    where: {
      StartDate: {
        [Op.between]: [WeekStartDate, WeekEndDate]
      }
    },
    include: {
      model: Matters
    }
  })

  res.send({
    code: 200,
    data: WeekData
  })
})

// 我的一月-獲取數據(目前是查到全部數據，後期再優化)
router.post('/MonthInfo', async function (req, res, next) {
  let Datt = new Date(req.body.Target)
  let MonthStartDate = Datt.getTime() - 604800000
  let MonthEndDate = 3628800000 + MonthStartDate

  const MonthDate = await Orders.findAll({
    where: {
      UserId: req.headers.uid
    },
    include: {
      model: Matters
    }
  })


  res.send({
    code: 200,
    data: MonthDate
  })
})

// 专注计时器-关联任务
router.post('/HasOrder', async function (req, res, next) {
  const Options = await Orders.findAll({
    where: {
      UserId: req.headers.uid,
      State: 0,
      StartDate: {
        [Op.gte]: req.body.myDate
      }
    },
  })

  res.send({
    code: 200,
    data: Options
  })
})

// 专注计时器-提交任务
router.post('/commitOrder', async function (req, res, next) {
  const Commit = await Orders.update({
    Duration: req.body.Duration,
    State: 1
  }, {
    where: {
      Id: req.body.Id
    }
  })

  res.send({
    code: 200,
    data: Commit,
    msg: '提交成功'
  })
})

// 数据统计-数据统计
router.post('/OneWeek', async function (req, res, next) {
  // 手动修正时区问题

  const DAYTIME = 86400000; // 一天时间常量
  let WeekTime = req.body.WeekStartTime; // 数据统计起始日
  let Month = req.body.Months // 月份
  let Year = req.body.Year // 年
  let Week = req.body.Week // 第几周
  let Day = req.body.Day // 天
  let LastTime = 0; // 数据统计时间限制
  let NextTime = 0; // 数据统计时间限制
  let regWork = []; // 折线图走势数据
  let regTime = []; // 柱状图走势数据
  let regMatter = []; // 饼状图走势数据
  let ContinuousDay = 0; // 连续有任务天数

  console.log(new Date(WeekTime));

  // 判断进行 周/月/年 数据清洗
  if (req.body.Commond == 1) {


    LastTime = WeekTime - 604800000
    NextTime = WeekTime + 604800000

    // 折线图数据
    let day = 0;
    let counttime = WeekTime;

    while (day < 7) {
      // 统计每天的工作量
      const DatData = await Orders.count({
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime + DAYTIME]
          }
        }
      })

      // 统计每天的专注时长
      const DayDuration = await Orders.sum('Duration', {
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime + DAYTIME]
          }
        }
      })


      counttime = counttime + DAYTIME
      regTime.push(Number((DayDuration / 3600).toFixed(2)))
      regWork.push(DatData)
      day++

      if (DatData > 0) {
        ContinuousDay++
      }
    }
  } else if (req.body.Commond == 2) {
    WeekTime = new Date(Year, Month, 1).getTime()
    LastTime = new Date(Year, Month - 1, 1).getTime()
    NextTime = new Date(Year, Month + 1, 1).getTime()

    // 折线图数据
    let week = 0;
    let counttime = WeekTime;

    while (week < new Date(Year, Month + 1, 0).getDate()) {
      // 统计每天的工作量
      const DatData = await Orders.count({
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime + DAYTIME]
          }
        }
      })

      // 统计每天的专注时长
      const DayDuration = await Orders.sum('Duration', {
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime + DAYTIME]
          }
        }
      })


      counttime = counttime + DAYTIME
      regTime.push(Number((DayDuration / 3600).toFixed(2)))
      regWork.push(DatData)
      week++

      if (DatData > 0) {
        ContinuousDay++
      }
    }
  } else if (req.body.Commond == 3) {
    WeekTime = new Date(Year + 1, 0, 1).getTime()
    LastTime = new Date(Year, 0, 1).getTime()
    NextTime = new Date(Year + 2, 0, 1).getTime()

    // 折线图数据
    let month = 0;
    while (month < 12) {
      // 统计每天的工作量
      let counttime = new Date(WeekTime).setMonth(month);
      let counttime2 = new Date(WeekTime).setMonth(month + 1);
      const DatData = await Orders.count({
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime2]
          }
        }
      })

      // 统计每天的专注时长
      const DayDuration = await Orders.sum('Duration', {
        where: {
          StartDate: {
            [Op.between]: [counttime, counttime2]
          }
        }
      })


      counttime = counttime + DAYTIME
      regTime.push(Number((DayDuration / 3600).toFixed(2)))
      regWork.push(DatData)
      month++

      if (DatData > 0) {
        ContinuousDay++
      }
    }
  }


  // 上周期的任务数据
  const LastWeekData = await Orders.findAll({
    where: {
      UserId: req.headers.uid,
      StartDate: {
        [Op.between]: [LastTime, WeekTime]
      }
    },
  })

  // 本周期任务数据
  const NowWeekData = await Orders.findAll({
    where: {
      UserId: req.headers.uid,
      StartDate: {
        [Op.between]: [WeekTime, NextTime]
      }
    },
  })

  // 事项任务数据
  const MatterData = await Matters.findAll({
    where: {
      UserId: req.headers.uid,
      EndDate: {
        [Op.gte]: WeekTime,
      },
      StartDate: {
        [Op.lte]: NextTime
      }
    },
    include: [{
      model: Orders,
      where: {
        StartDate: {
          [Op.between]: [WeekTime, NextTime]
        }
      }
    }]
  })

  function Rule(obj) {
    if (obj == 0) return 1
    else return obj
  }

  function ZZ(obj) {
    if (obj > 0) return '+' + obj
    else return obj
  }

  // 事件工作量
  let ComWorkCount = 0;
  let LastComWorkCount = 0;

  // 专注时长计算
  let NowWorkTime = 0;
  let LastWorkTime = 0;
  let NowTimeCount = 0;
  let LastTimeCount = 0;

  // 数据清洗
  for (let i = 0; i < MatterData.length; i++) {
    let target = {
      name: '',
      value: 0,
    }
    target.name = MatterData[i].Name
    for (let j = 0; j < MatterData[i].Orders.length; j++) {
      target.value = target.value + MatterData[i].Orders[j].Duration
    }
    // 转化为小时
    target.value = (target.value / 3600).toFixed(2)
    regMatter.push(target)
  }


  for (let i = 0; i < NowWeekData.length; i++) {
    NowWorkTime = NowWorkTime + NowWeekData[i].Duration

    // 筛选已完成的任务量
    if (NowWeekData[i].State == 1) {
      ComWorkCount++;
    }

    // 筛选进行番茄钟的任务量
    if (NowWeekData[i].Duration > 0) {
      NowTimeCount++;
    }
  }

  for (let i = 0; i < LastWeekData.length; i++) {
    LastWorkTime = LastWorkTime + LastWeekData[i].Duration

    // 筛选已完成的任务量
    if (LastWeekData[i].State == 1) {
      LastComWorkCount++;
    }

    // 筛选进行番茄钟的任务量
    if (LastWeekData[i].Duration > 0) {
      LastTimeCount++;
    }
  }

  // 本周期平均番茄时长
  const TimeAverage = ZZ((((NowWorkTime / 3600) / Rule(NowTimeCount))).toFixed(2))

  // 平均专注 周期增长率
  const TimeAveragerate = ZZ(((((NowWorkTime / 3600) / Rule(NowTimeCount))) / Rule((((LastWorkTime / 3600) / Rule(LastTimeCount))))).toFixed(2)) + "%"

  // 事件增长率
  const Weekrate = ZZ(((NowWeekData.length / Rule(LastWeekData.length)) * 100).toFixed(2)) + '%'

  // 时间增长率
  const WorkTimerate = ZZ((((NowWorkTime / 3600) / Rule(LastWorkTime / 3600)) * 100).toFixed(2)) + '%'

  // 本周/上周事件完成率
  const Comworkrate = ZZ((((ComWorkCount / Rule(NowWeekData.length)) * 100) / Rule(((LastComWorkCount / Rule(LastWeekData.length)) * 100))).toFixed(2)) + '%'


  res.send({
    code: 200,
    data: {
      NowWeekData: {
        WeekCount: NowWeekData.length,
        WorkTimeCount: (NowWorkTime / 3600).toFixed(2),
        ComWorkCount: ComWorkCount,
        NowTimeCount: NowTimeCount
      },
      LastWeekData: {
        WeekCount: LastWeekData.length,
        LastComWorkCount: LastComWorkCount
      },
      TimeAverage: TimeAverage,
      Weekrate: Weekrate,
      WorkTimerate: WorkTimerate,
      Comworkrate: Comworkrate,
      regWork: regWork,
      regTime: regTime,
      regMatter: regMatter,
      ContinuousDay: ContinuousDay,
      TimeAveragerate: TimeAveragerate,
      MatterData: MatterData
    }
  })
})

// 便利贴-创建
router.post('/NewNotes', async function (req, res, next) {
  const Commit = await Notes.create({
    text: req.body.text,
    UserId: req.headers.uid
  })

  res.send({
    code: 200
  })
})

// 便利贴-获取数据
router.post('/GetNotes', async function (req, res, next) {
  const Commit = await Notes.findAll({
    where: {
      UserId: req.headers.uid
    }
  })

  res.send({
    code: 200,
    data: Commit
  })
})


module.exports = router;